import greenfoot.*;  
import java.util.List;

public class Block extends Actor {
    private boolean isBomb = false;
    private boolean isFlagged = false;
    boolean isOpen = false;  // 将 isOpen 改为 public 或提供一个 getter 方法

    public boolean getFlag() {      
        return isFlagged;
    }

    public void setBomb() {         
        isBomb = true;
    }

    public boolean getBomb() {     
        return isBomb;
    }

    public boolean isOpen() {  // 添加此方法
        return isOpen;
    }

    public void act() {
        checkMouse();
    }    

    public void checkMouse() {     
        if (Greenfoot.mouseClicked(this)) {       
            MouseInfo mouse = Greenfoot.getMouseInfo();
            if (mouse.getButton() == 3 && !isOpen) {
                if (!isFlagged) {
                    setImage("BlockFlagged.png");
                    isFlagged = true;
                } else {
                    setImage("Block.png");
                    isFlagged = false;
                }
            }
            if (mouse.getButton() == 1 && !isFlagged) {
                if (isBomb) {
                    GameWorld world = (GameWorld) getWorld();
                    world.showAllBomb();
                    Greenfoot.playSound("bomb.wav");
                } else {
                    openBlock(this);
                }
            }
        } 
    }

    private void openBlock(Block block) {        
        block.isOpen = true;  // 设置为已翻开
        int bombNumber = block.getBombNumber(block);
        block.setImage("BlockClicked[" + bombNumber + "].png");
        if (bombNumber == 0) {
            List<Block> blocks = block.getNeighbours(1, true, Block.class);
            for (Block nBlock : blocks) {
                if (!nBlock.isOpen) {
                    openBlock(nBlock);
                }
            }
        }
    }

    private int getBombNumber(Block block) {
        int bombNumber = 0;
        List<Block> blocks = block.getNeighbours(1, true, Block.class);
        for (Block nBlock : blocks) {
            if (nBlock.getBomb()) {
                bombNumber++;
            }
        }  
        return bombNumber;
    }
}
